package com.iwhalecloud.bss.kite.cucc.web.controller.scene;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.cart.client.api.inf.base.payrelation.IKiteCartCommonQueryService;
import com.iwhalecloud.bss.kite.cart.client.dto.req.payrelation.KiteCartChannelStaffReqDTO;
import com.iwhalecloud.bss.kite.cart.client.dto.rsp.payrelation.KiteCartChannelStaffRspDTO;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.dto.inst.InstAttrDTO;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.*;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.ILocalQueryDevInfoService;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IUnicomRegionService;
import com.iwhalecloud.bss.kite.cucc.client.api.inf.IInfServiceBus;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.ChannelKindDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.devInfo.response.QueryChannelInfoSerRsp;
import com.iwhalecloud.bss.kite.cucc.client.dto.devInfo.response.QueryDeveloperInfoRespDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.inf.req.QryDevloperReqDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr.PersonAttrDealService;
import com.iwhalecloud.bss.kite.cucc.web.service.bigdata.util.ProductAttrHandler;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.dto.KiteAttrDTO;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.transaction.KiteTransactional;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.iwhalecloud.bss.kite.service.util.CopyToDtoUtil;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.SceneModule;
import com.iwhalecloud.bss.kite.web.service.accept.service.SceneTemplateService;
import com.ztesoft.bss.common.bo.LoginInfo;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController("cuccPersonAttr")
@RequestMapping("/cuccPersonAttr")
@Api(tags = {"/cuccPersonAttr - 四类人信息属性处理"
})
public class LocalPersonAttrController {

    @Autowired
    private PersonAttrDealService personAttrDealService;

    @Autowired
    private ILocalQueryDevInfoService queryDevInfoService;

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IUnicomRegionService unicomRegionService;

    @Autowired
    private OperateInstAttrService operateInstAttrService;
    @Autowired
    private SceneTemplateService sceneTemplateService;



    @KiteTransactional
    @ApiOperation(value = "更新四类人信息", notes = "更新四类人信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "fieldName", value = "属性规格编码", required = true),
        @ApiImplicitParam(name = "value", value = "修改值", required = true),
        @ApiImplicitParam(name = "valueDesc", value = "展示值", required = true),
        @ApiImplicitParam(name = "moduleId", value = "模块编码", required = true),
        @ApiImplicitParam(name = "sceneInstId", value = "场景实例id", required = false)
    })
    @PutMapping
    public DataResult<List<CommonAttrVO>> updateCommonAttr(@RequestParam String fieldName, @RequestParam String value,
                                                           @RequestParam String valueDesc, @RequestParam(required = false) String moduleId,
                                                           @RequestParam(required = false) String sceneInstId) {

        if (KiteStringUtils.isEmpty(sceneInstId)) {
            sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        }
        DataResult<Boolean> apply = personAttrDealService
            .apply(KiteWebContext.getContext().getCurrentSceneInstId(), fieldName, value, valueDesc, moduleId);
        // 根据模块返回对应的属性
        List<CommonAttrVO> commonAttrList = new ArrayList<>();
        DataResult<List<CommonAttrVO>> result =ErrorConsts.SUCCESS.getResult(commonAttrList);
        String tacheCode = querySceneInstService.getExtParameterValue(sceneInstId,"nodeCode");
        String serviceOfferId = querySceneInstService.getExtParameterValue(sceneInstId,"serviceOfferId");
        String offerInstId = querySceneInstService.getSceneInst(sceneInstId).getRootInstId();
        //        String objId = querySceneInstService.getOfferInstAttrValue(KiteWebContext.getContextNew().getCustId(), offerInstId, "cateId");
        String offerId = querySceneInstService.getOfferInst(KiteWebContext.getContextNew().getCustId(), offerInstId)
            .getSpecId();
        String objId = OfferCache.get(offerId).getCateId();
        List<KiteAttr> commonAttrsByObjId = querySceneInstService
            .listCommonAttrsByObjIdAndModuleId(sceneInstId, objId, moduleId);
        List<KiteAttr> commonAttrs = querySceneInstService.listCommonAttrsByObjIdAndModuleId(sceneInstId, null, moduleId);
        if (KiteListUtils.isNotEmpty(commonAttrsByObjId)) {
            commonAttrs.addAll(commonAttrsByObjId);
        }
        List<InstAttrDTO> instAttrDTOList = CopyToDtoUtil.transInstAttrDtoList(commonAttrs);
        String pop = StringUtils.EMPTY;
        if (KiteListUtils.isNotEmpty(instAttrDTOList)) {
            instAttrDTOList.removeIf(
                instAttrDTO -> !KiteStringUtils.equalsAny(instAttrDTO.getShowType(),KeyConsts.PROD_ATTR_SHOW_TYPE_D, KeyConsts.PROD_ATTR_SHOW_TYPE_M));
            commonAttrList = KiteListUtils.isNotEmpty(instAttrDTOList) ?
                instAttrDTOList.stream().map(attrDTO -> KiteBeanUtils.transform(attrDTO, CommonAttrVO.class))
                    .collect(Collectors.toList()) :
                Collections.emptyList();
            SceneModule sceneModule =sceneTemplateService.getSceneModuleById(moduleId);
            commonAttrList.forEach(commonAttrVO -> {
                commonAttrVO.setReminder(reminder(sceneModule.getKiteModule().getLayoutPage(),sceneModule.getKiteModule().getModuleId(),offerId,commonAttrVO.getFieldName()));
            });
            pop=    pop(sceneModule.getKiteModule().getLayoutPage(),sceneModule.getKiteModule().getModuleId(),objId,fieldName,value,tacheCode,serviceOfferId);
        }
        // 产品属性修改
        if(KiteStringUtils.isEqual(fieldName, "300000203")){
            List<KiteInst> prodInstList = querySceneInstService.listInsts(sceneInstId, Collections.singletonList(InstType.PROD_INST));
            for (KiteInst prodInst : prodInstList) {
                CuccContextCustDTO custDTO = (CuccContextCustDTO) KiteWebContext.getContext().getCust();
                KiteAttr prodAttr = querySceneInstService.getProdInstAttr(custDTO.getCustId(), prodInst.getInstId(), "300000203");
                if(!KiteObjectUtils.isEmpty(prodAttr) && !KiteStringUtils.isEqual(prodAttr.getValue(), value)){
                    prodAttr.setValue(value);
                    prodAttr.setValueDesc(valueDesc);
                    operateInstAttrService.setAttrValue(prodInst, prodAttr.getFieldName(), value, sceneInstId, null);
                }
            }
        }
        //ProductAttrHandler.getInst().AddProdSelectToAttr(sceneInstId,fieldName);
        //场景回刷
        //AcceptEngineUtil.refreshScene(apply);
        result.setPop(pop);
        result.setResultObject(commonAttrList);
        return result;
    }

    @KiteTransactional
    @ApiOperation(value = "更新四类人信息多值", notes = "更新四类人信息多值")
    @ApiImplicitParams({@ApiImplicitParam(name = "attrs", value = "公共属性数组", required = true),
        @ApiImplicitParam(name = "sceneInstId", value = "场景实例id", required = false)
    })
    @PutMapping("/updateListPersonInfo")
    public DataResult<Boolean> updateCommonAttrs(@RequestBody List<KiteAttrDTO> attrs,@RequestParam(required = false) String sceneInstId) {
        if(KiteStringUtils.isEmpty(sceneInstId)){
            sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        }
        DataResult<Boolean> apply = personAttrDealService
            .apply(sceneInstId, attrs);
        //AcceptEngineUtil.refreshScene(apply);
        return apply;
    }

    @KiteTransactional
    @ApiOperation(value = "获取指定四类人的更多信息", notes = "获取指定四类人的更多信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例Id", required = true),
        @ApiImplicitParam(name = "objType", value = "四类人标识", required = true)
    })
    @GetMapping("/getMoreAttrByObjType")
    public DataResult<List<CommonAttrVO>> getMoreByObjType(@RequestParam(required = false) String sceneInstId,
                                                           @RequestParam String objType) {
        List<CommonAttrVO> list = personAttrDealService.getMoreByObjType(sceneInstId, objType);
        return ErrorConsts.SUCCESS.getResult(list);
    }

    @KiteTransactional
    @ApiOperation(value = "获取渠道分类信息", notes = "获取渠道分类信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "sceneInstId", value = "场景实例Id", required = true),
        @ApiImplicitParam(name = "chnlKindId", value = "渠道分类ID", required = false),
        @ApiImplicitParam(name = "chnlCode", value = "渠道编码", required = false),
        @ApiImplicitParam(name = "chnlName", value = "渠道名称", required = false),
        @ApiImplicitParam(name = "pageNum", value = "页数", required = false),
        @ApiImplicitParam(name = "pageSize", value = "分页大小", required = false)
    })
    @GetMapping("/getChanelType")
    public DataResult<List<ChannelKindDTO>> getChanelType(@RequestParam(required = false) String sceneInstId,
                                                          @RequestParam(required = false) String chnlKindId,
                                                          @RequestParam(required = false) String chnlCode,
                                                          @RequestParam(required = false) String chnlName,
                                                          @RequestParam(required = false) String pageNum,
                                                          @RequestParam(required = false) String pageSize) {
        String provinceCode = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        if (!KiteStringUtils.isEmpty(provinceCode) && provinceCode.startsWith("48")) {
            List<ChannelKindDTO> list = Lists.newArrayList();
            PageInfo<QueryChannelInfoSerRsp> page = queryDevInfoService
                .queryDevInfoChanelInfo(chnlCode, chnlName, chnlKindId, pageSize, pageNum);
            if (!KiteListUtils.isEmpty(page.getList())) {
                page.getList().forEach(channel -> {
                    ChannelKindDTO channelKindDTO = new ChannelKindDTO();
                    channelKindDTO.setCodeValue(channel.getChnlCode());
                    channelKindDTO.setCodeValueName(channel.getChnlName());
                    list.add(channelKindDTO);
                });
            }
            return ErrorConsts.SUCCESS.getResult(list);
        }
        if(KiteStringUtils.isEmpty(sceneInstId)){
            sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        }
        List<ChannelKindDTO> list = queryDevInfoService.queryDevInfoChanelType();
        KiteAttr attr = querySceneInstService.getCommonAttrsByFieldName(sceneInstId, LocalKeyConsts.IS_LEADER_SIGN, "113");
        if(Objects.isNull(attr)) {
            attr = querySceneInstService.getCommonAttrsByFieldName(sceneInstId, LocalKeyConsts.IS_LEADER_SIGN_NEW, "113");
        }
        if(Objects.isNull(attr)) {
            return ErrorConsts.SUCCESS.getResult(list);
        }
        if(KiteStringUtils.isNotBlank(attr.getValue())){
            if(KiteStringUtils.equals(attr.getValue(),"1")){
                list = unicomRegionService.queryChannel();
            }
        }
        if (KiteListUtils.isEmpty(list)) {
            return ErrorConsts.SUCCESS.getResult(Lists.newArrayList());
        }
        return ErrorConsts.SUCCESS.getResult(list);
    }

    @KiteTransactional
    @ApiOperation(value = "获取渠道信息", notes = "获取渠道信息")
    @GetMapping("/getChanelInfo")
    public DataResult<PageInfo<QueryChannelInfoSerRsp>> getChanelInfo(String chnlCode, String chnlName,
                                                                      String chnlKindId,String channelKindId,String channelName, @RequestParam(required = false) String pageSize,
                                                                      @RequestParam(required = false) String pageNum) {
        chnlKindId = KiteStringUtils.isEmpty(chnlKindId)?channelKindId:chnlKindId;//兼容前端省份入参
        chnlName = KiteStringUtils.isEmpty(chnlName)?channelName:chnlName;

        PageInfo<QueryChannelInfoSerRsp> list = queryDevInfoService
            .queryDevInfoChanelInfo(chnlCode, chnlName, chnlKindId, pageSize, pageNum);
        if(KiteStringUtils.isNotBlank(chnlKindId)&&KiteStringUtils.equals(chnlKindId,"111111")){
            List<QueryChannelInfoSerRsp> list1 = unicomRegionService.queryChannelByChannelLevel(chnlKindId);
            list = PageInfoUtils.coverToPageTotal(list1, Integer.parseInt(pageNum), Integer.parseInt(pageSize), list1.size());
        }
        if (Objects.isNull(list) || KiteListUtils.isEmpty(list.getList())) {
            return ErrorConsts.SUCCESS.getResult(new PageInfo<>(new ArrayList<>()));
        }
        return ErrorConsts.SUCCESS.getResult(list);
    }

    @KiteTransactional
    @ApiOperation(value = "获取渠道发展人", notes = "获取渠道发展人")
    @GetMapping("/getChanelStaff")
    public DataResult<PageInfo<QueryDeveloperInfoRespDTO>> getChanelStaff(String chnlCode, String devName,
                                                                          String devCode, Integer pageSize, Integer pageNum,String channelCode) {
        chnlCode = KiteStringUtils.isEmpty(chnlCode)?channelCode:chnlCode;
        QryDevloperReqDTO qryDevloperReqDTO = new QryDevloperReqDTO(chnlCode,devName,devCode,null,pageSize,pageNum,null);
        PageInfo<QueryDeveloperInfoRespDTO> queryDeveloperInfoRespDTOPageInfo = queryDevInfoService
            .queryDevInfoChanelStaff(qryDevloperReqDTO);
        PageInfo<QueryDeveloperInfoRespDTO> list = queryDeveloperInfoRespDTOPageInfo;
        if (Objects.isNull(list) || KiteListUtils.isEmpty(list.getList())) {
            return ErrorConsts.SUCCESS.getResult(new PageInfo<>(new ArrayList<>()));
        }
        return ErrorConsts.SUCCESS.getResult(list);
    }

    @ApiOperation(value = "通过接口查询区域数据(批量)", notes = "通过接口查询区域数据(批量)")
    @PostMapping("/insertAreaInfosBatch")
    public DataResult<String> insertAreaInfosBatch() {
        IInfServiceBus infServiceBus = SpringUtil.getBean(IInfServiceBus.class);
        infServiceBus.insertAreaInfoBatch("10");
        infServiceBus.insertAreaInfoBatch("20");
        infServiceBus.insertAreaInfoBatch("30");
        return ErrorConsts.SUCCESS.getResult("插入完成");
    }
    @KiteTransactional
    @ApiOperation(value = "通过关键字获取发展人", notes = "通过关键字获取发展人")
    @GetMapping("/getDevList")
    public DataResult<PageInfo<QueryDeveloperInfoRespDTO>> getDevList(String chnlCode, String devName,
                                                                      String devCode, String devPhone, Integer pageSize, Integer pageNum) {
        QryDevloperReqDTO qryDevloperReqDTO = new QryDevloperReqDTO(chnlCode,devName,devCode,devPhone,pageSize,pageNum,null);
        Map operUserInfo = new HashMap();
        LoginInfo loginInfo = ContextUtil.getLoginInfo();
        operUserInfo.put("provinceCode",loginInfo.getUserInfo().getPostProvinceNbr());
        operUserInfo.put("islocal","T");
        qryDevloperReqDTO.setOperUserInfo(operUserInfo);
        DataResult<PageInfo<QueryDeveloperInfoRespDTO>>  list = queryDevInfoService
            .queryDevInfoChanelByKeyCode(qryDevloperReqDTO);
        return list;
    }
    private static String reminder(String layoutPage,String moduleId,String offerId,String fieldName){
        List<DcPublic> publics = DcPublicCache.getByPcode("2021110409", "reminder",layoutPage);
        String reminder= StringUtils.EMPTY;
        for(DcPublic dcPublic:publics){
            if(dcPublic.getCodea().contains(offerId)&&dcPublic.getCoded().equals(moduleId)&&dcPublic.getCodeb().equals(fieldName)){
                reminder=dcPublic.getCodec();
            }
        }
        return reminder;
    }
    private static String pop(String layoutPage,String moduleId,String objId,String fieldName,String value,String tacheCode,String serviceOfferId){
        String pcode = serviceOfferId+":"+tacheCode+":"+layoutPage;
        List<DcPublic> publics = DcPublicCache.getByPcode("2021110409", "POP",pcode);
        String pop= StringUtils.EMPTY;
        for(DcPublic dcPublic:publics){
            if(dcPublic.getCodea().contains(objId)&&dcPublic.getCodee().equals(moduleId)&&dcPublic.getCodeb().equals(fieldName)&&dcPublic.getCodec().equals(value)){
                pop=dcPublic.getCoded();
            }
        }
        return pop;
    }
}
